package main

import (
	"crypto/tls"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"regexp"
	"strconv"
	"strings"
)

var status = 0

func main()  {

	// 先获取网页内容
	var res string
	getBody("https://www.ui.cn", &res)
	//fmt.Println(res)
	reg :=regexp.MustCompile(`/<img .*src="([^<]*)" [^<]*>/`)
	err := ioutil.WriteFile("./ui.cn.html", []byte(res), 666)
	checkErr(err)
	fmt.Println(reg.FindAllStringSubmatch(res, 2))
	res = strings.ReplaceAll(res, "\n", "")
	res = strings.ReplaceAll(res, " ", "")
	res = strings.ReplaceAll(res, "\t", "")
	strArr := strings.Split(res, "<")
	var resArr []string
	for _,v := range strArr{
		if  strings.HasPrefix(strings.TrimSpace(v), "img"){
			tmp := strings.Split(v, "\"")
			for _, val := range tmp{
				if strings.HasPrefix(val, "http") {
					resArr = append(resArr, val)
				}
			}
		}
	}
	err = os.Mkdir("./imgs", 0666)
	checkErr(err)
	for k, v := range resArr{
		status ++
		Worker(k, v)
	}
	for status != 0{

	}
	fmt.Println(resArr)
}

func getBody(url string, result *string) {

	// 创建传送带, 跳过证书校验
	tr := &http.Transport{
		TLSClientConfig:&tls.Config{InsecureSkipVerify:true},
	}
	client := &http.Client{Transport:tr}

	// 获取网页内容
	response, err := client.Get(url)
	checkErr(err)
	defer func() {
		err = response.Body.Close()
		checkErr(err)
	}()

	// 读取并转换结果
	res, err := ioutil.ReadAll(response.Body)
	checkErr(err)
	*result = string(res)
}

func Worker(k int, v string)  {
	var img string
	getBody(v, &img)
	err := ioutil.WriteFile("./imgs/"+ strconv.Itoa(k) + v[len(v)-4:], []byte(img), 666)
	checkErr(err)
	status--
}

func checkErr(err error){
	if err != nil {
		panic(err)
	}
}
